package com.lntea.netty.mqtt.heartBeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.mqtt.*;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

/**
 * Title: MqttHeartBeatClientHandler.java<br>
 * Description:  <br>
 * Copyright: Copyright (c) 2015<br>
 * Company: 北京云杉世界信息技术有限公司<br>
 *
 * @author lichao
 * @date 2019/11/19 11:52
 */
public class MqttHeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    private static final String PROTOCOL_NAME_MQTT_3_1_1 = "MQTT";
    private static final int PROTOCOL_VERSION_MQTT_3_1_1 = 4;

    private final String clientId;
    // private int number;

    public MqttHeartBeatClientHandler(String clientId) {
        this.clientId = clientId;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // discard messages
        MqttMessage mqttMessage = (MqttMessage) msg;
        System.out.println("Received MQTT message: " + mqttMessage);
        ReferenceCountUtil.release(msg);

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT,
                false, MqttQoS.AT_MOST_ONCE, false, 0);
        MqttConnectVariableHeader mqttConnectVariableHeader = new MqttConnectVariableHeader(PROTOCOL_NAME_MQTT_3_1_1,
                PROTOCOL_VERSION_MQTT_3_1_1, false, false, false, 0, false, false, 20);
        // clientId不能为空
        MqttConnectPayload mqttConnectPayload = new MqttConnectPayload("", null, null, null, "".getBytes());
        MqttConnectMessage mqttConnectMessage = new MqttConnectMessage(mqttFixedHeader, mqttConnectVariableHeader, mqttConnectPayload);
        ctx.writeAndFlush(mqttConnectMessage);
        System.out.println("Sent Connect");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            // if (number++ < 3) {
                MqttFixedHeader pingreqFixedHeader = new MqttFixedHeader(MqttMessageType.PINGREQ,
                        false, MqttQoS.AT_MOST_ONCE, false, 0);
                MqttMessage pingreqMessage = new MqttMessage(pingreqFixedHeader);
                ctx.writeAndFlush(pingreqMessage);
                System.out.println("Sent PINGREQ");
                // System.out.println("Sent PINGREQ(number=" + number + ")");
            //}
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
